package com.mfoyou.agent.web.utils.wx;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class WXPICUtil {

    private static final Logger logger = LoggerFactory.getLogger(WXPICUtil.class);

    /**
     * 测试是 api-d 开头
     */
    public static String BG_PIC_URL_TYPE_1 = " http://api.aimizhu.com/tinypig/img/type1.png";
    public static String BG_PIC_URL_TYPE_2 = " http://api.aimizhu.com/tinypig/img/type2.png";
    public static String BG_PIC_URL_TYPE_3 = " http://api.aimizhu.com/tinypig/img/type3.png";
    private static final String WXQRPIC = "";

    public static BufferedImage getPic(String token, Integer type, String productUrl, String productPrice, String productName, String page, String scene) throws Exception {
        InputStream wxPic = getWxPic(token, page, scene);
        switch (type) {
            case 1:
                return drawPicTypeOne(wxPic, null);
            case 2:
                return drawPicTypeTwo(wxPic, null);
            case 3:
                return drawPicTypeThree(wxPic, productUrl, productPrice, productName);
        }
        return null;
    }

    public static InputStream getWxPic(String token, String page, String scene) throws Exception {
        JSONObject wxJson = new JSONObject();
        wxJson.put("page", page);
        wxJson.put("scene", scene);
        String data = wxJson.toJSONString();
        logger.info("data={}", data);
        InputStream printPic = sendPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token, data); //太阳码
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(printPic, "utf-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        JSONObject jsonObject = JSONObject.parseObject(stringBuilder.toString());
        logger.info("jsonObject={}", jsonObject);
        if (jsonObject.containsKey("errcode")) {
            return null;
        }
        return printPic;
    }

    /**
     * 请求微信
     *
     * @param url
     * @param data
     * @return
     */
    public static InputStream sendPost(String url, String data) {
        OutputStreamWriter out;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(data);
            out.flush();
            return conn.getInputStream();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 大小缩放
     *
     * @param picStream
     * @param w
     * @param h
     * @return
     * @throws Exception
     */
    public static BufferedImage zoomImage(InputStream picStream, int w, int h) throws Exception {

        double wr = 0, hr = 0;

        //读取图片
        BufferedImage bufImg;
        if (picStream == null) {
            //二维码
            bufImg = ImageIO.read(new FileInputStream("/opt/app/agent-web/1.jpg"));
        } else {
            bufImg = ImageIO.read(picStream);
        }
        //设置缩放目标图片模板
        Image Itemp;

        if (bufImg == null) {
            return null;
        }

        //获取缩放比例
        wr = w * 1.0 / bufImg.getWidth();
        hr = h * 1.0 / bufImg.getHeight();

        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);

        Itemp = ato.filter(bufImg, null);

        return (BufferedImage) Itemp;
    }

    /**
     * 类型1
     *
     * @param wxPic
     * @param headUrl
     */
    public static BufferedImage drawPicTypeOne(InputStream wxPic, String headUrl) {
        BufferedImage qCode;
        BufferedImage bg;
        BufferedImage head;
        URL url;
        HttpURLConnection httpUrl;
        try {
            //获取背景图片2
            url = new URL(BG_PIC_URL_TYPE_1);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bg = ImageIO.read(httpUrl.getInputStream());

            qCode = zoomImage(wxPic, 242, 242);
            if (qCode == null) return null;

            //获取用户头像
            url = new URL(headUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            head = zoomImage(httpUrl.getInputStream(), 72, 72);

            Graphics2D g = bg.createGraphics();
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
            //写入二维码
            g.drawImage(qCode, 245, 314, qCode.getWidth(), qCode.getHeight(), null);
            //叠加头像
            g.drawImage(head, 339, 1144, head.getWidth(), head.getHeight(), null);
            g.dispose();
            bg.flush();
            qCode.flush();
            return bg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 类型2
     *
     * @param wxPic
     * @param headUrl
     */
    public static BufferedImage drawPicTypeTwo(InputStream wxPic, String headUrl) {
        BufferedImage qCode;
        BufferedImage bg;
        BufferedImage head;
        URL url;
        HttpURLConnection httpUrl;
        try {

            //获取背景图片2
            url = new URL(BG_PIC_URL_TYPE_2);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bg = ImageIO.read(httpUrl.getInputStream());

            qCode = zoomImage(wxPic, 152, 152);
            if (qCode == null) return null;
            url = new URL(headUrl); //获取用户头像
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            head = zoomImage(httpUrl.getInputStream(), 151, 151);

            Graphics2D g = bg.createGraphics();
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
            //写入二维码
            g.drawImage(qCode, 547, 1133, qCode.getWidth(), qCode.getHeight(), null);
            //叠加头像
            g.drawImage(head, 50, 1133, head.getWidth(), head.getHeight(), null);
            g.dispose();
            bg.flush();
            qCode.flush();
            return bg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static IndexColorModel getColorModel() {
        byte[] r = new byte[256];
        byte[] g = new byte[256];
        byte[] b = new byte[256];
        for (int i = 0; i < 256; i++) {
            r[i] = (byte) i;
            g[i] = (byte) i;
            b[i] = (byte) i;
        }
        return new IndexColorModel(8, 256, r, g, b);
    }

    /**
     * 类型3
     *
     * @param
     * @param wxPic
     * @param productUrl
     */
    public static BufferedImage drawPicTypeThree(InputStream wxPic, String productUrl, String productPrice, String productName) {
        BufferedImage qCode;
        int width = 750;
        int height = 1200;
        BufferedImage bg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        BufferedImage goods;
        BufferedImage head;

        URL url;
        HttpURLConnection httpUrl;
        try {
            qCode = zoomImage(wxPic, 200, 200);
            if (qCode == null) return null;

            //获取商品
            url = new URL(productUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            goods = zoomImage(httpUrl.getInputStream(), 682, 682);
            Graphics2D g = bg.createGraphics();
            g.setBackground(Color.white);
            g.clearRect(0, 0, width, height);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
            //写入二维码
            g.drawImage(qCode, 520, 925, qCode.getWidth(), qCode.getHeight(), null);
            //写入商品图片
            System.out.println(goods.toString());
            g.drawImage(goods, 34, 34, goods.getWidth(), goods.getHeight(), null);
            int displayLength = (width - 34 * 2) / 48;
            logger.info("顯示長度={}", displayLength);
            logger.info("字體長度長度={}", productName.length());
            List<String> list = new ArrayList<>();
            while (productName.length() > displayLength) {
                list.add(productName.substring(0, displayLength));
                productName = productName.substring(displayLength);
            }
            list.add(productName);
            int y = 787;
            for (String str : list.size() >= 2 ? list.subList(0, 2) : list) {
                Font font2 = new Font("PingFang-SC-Bold", Font.BOLD, 48);
                g.setColor(Color.BLACK);
                g.setFont(font2);
                g.drawString(str, 40, y);
                y += 60;
                logger.info("生成名字");
            }

            Font font1 = new Font("PingFang-SC-Bold", Font.BOLD, 61);
            Color color1 = new Color(255, 71, 71);//new Color(0, 0, 255);
            g.setColor(color1);
            g.setFont(font1);
            g.drawString(productPrice, 90, 920);
            logger.info("生成价格");

            Font font3 = new Font("PingFang-SC-Bold", Font.BOLD, 30);
            Color color3 = new Color(255, 71, 71);//new Color(0, 0, 255);
            g.setColor(color3);
            g.setFont(font3);
            g.drawString("￥", 50, 920);
            logger.info("生成价格符号");
            Font font4 = new Font("PingFang-SC-Bold", Font.BOLD, 18);
            Color color4 = new Color(96, 96, 96);//new Color(0, 0, 255);
            g.setColor(color4);
            g.setFont(font4);
            g.drawString("扫描或者长按识别小程序", 515, 1150);
            logger.info("生成提示");
            g.dispose();
            bg.flush();
            qCode.flush();
            return bg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }


    /**
     * 绘画测试
     */
    public static void drawPic() {
        BufferedImage qCode = null;
        BufferedImage bg = null;
        try {
            qCode = ImageIO.read(new FileInputStream("F:\\work\\img\\2222.jpg"));//二维码
            bg = ImageIO.read(new FileInputStream("F:\\work\\img\\1111.png"));//背景图
            Graphics2D g = bg.createGraphics();
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
            g.drawImage(qCode, 250, 350, 250, 250, null);
            g.dispose();
            bg.flush();
            qCode.flush();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bg, "png", new File("F:\\work\\img\\test.jpg"));//本地调试使用
            baos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {
        String token = "18_SitDswRJ_KwD_8NGVRTTPPvkwZeofPY4_Zhh4yFSXiqbGebTX9bGl_5d83wRHAnJhEbaX9zbDOzNQPdOygaFgWP1sShIytCGaCoKvkPwOL3preYge1IIv3rGdUsQVJcADAAFT";
        String productUrl = "http://imgd.mfoyou.com/group1/M00/00/13/rBOwXVtF89SAGFBYAAAPlYiw-Uw513.png";
        String productPrice = "55";
        String productName = "我要把它以每300字为一段截取出来";
        Object pic = getPic(token, 3, productUrl, productPrice, productName, null, null);
        System.out.println(pic);
    }


}





